package org.tron.trident.job;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.tron.trident.entity.Account;
import org.tron.trident.service.AccountService;
import org.tron.trident.service.TRXService;
import org.tron.trident.service.Trc20Service;

import java.math.BigInteger;
import java.util.Date;
import java.util.List;
@Component
public class CoinCollectionJob {
    @Value("${tron.contract-address}")
    private String contractAddress;//hex格式

    private Logger logger = LoggerFactory.getLogger(CoinCollectionJob.class);
    @Autowired
    private AccountService accountService;
    @Autowired
    private TRXService trxService;
    @Autowired
    private Trc20Service trc20Service;


     /*为用户充值trx，充当gas*/
     @Scheduled(cron = "0 0/1 * * * ?")
    public void rechargeMinerFee(){
        logger.info(new Date()+"转矿工费任务开始");
        List<Account> accountList = accountService.findAll();
        logger.info("账户:"+accountList);
        accountList.stream().forEach(account -> {
            //查询合约下账户的余额
            BigInteger trc20Balance = trc20Service.balanceOf(account.getAddress());
            logger.info(account.getAddress()+"余额："+trc20Balance);
            BigInteger feeAmt = this.subtract(trc20Balance.divide(new BigInteger("1000000")));
            if(feeAmt.compareTo(new BigInteger("0"))!=0){
                //转账矿工费
                trc20Service.feeAmtTransfer(account,Long.valueOf(feeAmt.toString()));
            }
        });

    }
    public BigInteger subtract(BigInteger trc20Balance){
        if(trc20Balance.compareTo(new BigInteger("0"))==0){
            return new BigInteger("0");

        }
        if(trc20Balance.compareTo(new BigInteger("10000",16))<0){
            return new BigInteger("5");
        }else{
            //超过一万为万五手续费
             return trc20Balance.multiply(new BigInteger("5").divide(new BigInteger("10000")));
        }
    }
}
